//
//  QueryTrackViewController.m
//  AMapTrack_Demo
//
//  Created by liubo on 2018/7/26.
//  Copyright © 2018年 autonavi. All rights reserved.
//

#import "QueryTrackViewController.h"
#import <AMapTrackKit/AMapTrackKit.h>
#import <MAMapKit/MAMapKit.h>
#import "APIKey.h"

@interface QueryTrackViewController ()<AMapTrackManagerDelegate, MAMapViewDelegate>
{
    UIButton *_queryTrackInfoBtn;
    UIButton *_queryTrackHstBtn;
    UISegmentedControl *_correctionSegment;
    UISegmentedControl *_recoupSegment;
    
    BOOL _correction;
    BOOL _recoup;
}

@property (nonatomic, strong) AMapTrackManager *trackManager;

@property (nonatomic, strong) MAMapView *mapView;

@end

@implementation QueryTrackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.toolbar.translucent = YES;
    self.navigationController.toolbarHidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self initMapView];
    
    [self initButtons];
    
    [self initTrackManager];
}

- (void)dealloc {
    [self.trackManager stopService];
    self.trackManager.delegate = nil;
    self.trackManager = nil;
    
    [self.mapView removeFromSuperview];
    self.mapView.delegate = nil;
    self.mapView = nil;
}

- (void)initMapView
{
    if (self.mapView == nil)
    {
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 70)];
        [self.mapView setDelegate:self];
        [self.mapView setZoomLevel:13.0];
        [self.mapView setShowsUserLocation:YES];
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow];
        
        [self.view addSubview:self.mapView];
    }
}

- (void)initButtons
{
    _queryTrackInfoBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _queryTrackInfoBtn.frame = CGRectMake(10, CGRectGetMaxY(self.view.bounds) - 165, 100, 25);
    _queryTrackInfoBtn.backgroundColor = [UIColor whiteColor];
    _queryTrackInfoBtn.layer.borderWidth = 1;
    _queryTrackInfoBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    [_queryTrackInfoBtn setTitle:@"查询轨迹信息" forState:UIControlStateNormal];
    [_queryTrackInfoBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_queryTrackInfoBtn addTarget:self action:@selector(queryTrackInfoAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_queryTrackInfoBtn];
    
    _queryTrackHstBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _queryTrackHstBtn.frame = CGRectMake(120, CGRectGetMaxY(self.view.bounds) - 165, 100, 25);
    _queryTrackHstBtn.backgroundColor = [UIColor whiteColor];
    _queryTrackHstBtn.layer.borderWidth = 1;
    _queryTrackHstBtn.layer.borderColor = [UIColor darkGrayColor].CGColor;
    [_queryTrackHstBtn setTitle:@"查询轨迹历史" forState:UIControlStateNormal];
    [_queryTrackHstBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_queryTrackHstBtn addTarget:self action:@selector(queryTrackHisAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_queryTrackHstBtn];
    
    _correctionSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"不纠偏", @"纠偏", nil]];
    _correctionSegment.frame = CGRectMake(10, CGRectGetMaxY(self.view.bounds) - 135, 100, 25);
    [_correctionSegment addTarget:self action:@selector(correctionSegmentAction:) forControlEvents:UIControlEventValueChanged];
    _correctionSegment.selectedSegmentIndex = 0;
    _correctionSegment.backgroundColor = [UIColor whiteColor];
    [_correctionSegment sizeToFit];
    [self.view addSubview:_correctionSegment];
    
    _recoupSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"不自动补点", @"自动补点", nil]];
    _recoupSegment.frame = CGRectMake(120, CGRectGetMaxY(self.view.bounds) - 135, 100, 25);
    [_recoupSegment addTarget:self action:@selector(recoupSegmentAction:) forControlEvents:UIControlEventValueChanged];
    _recoupSegment.selectedSegmentIndex = 0;
    _recoupSegment.backgroundColor = [UIColor whiteColor];
    [_recoupSegment sizeToFit];
    [self.view addSubview:_recoupSegment];
}

- (void)initTrackManager {
    if ([kAMapTrackServiceID length] <= 0 || [kAMapTrackTerminalID length] <= 0) {
        _queryTrackInfoBtn.enabled = NO;
        _queryTrackHstBtn.enabled = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"您需要指定ServiceID和TerminalID才可以使用轨迹服务"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    //Service ID 需要根据需要进行修改
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = kAMapTrackServiceID;
    
    //初始化AMapTrackManager
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    
    //配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
}

#pragma mark - Actions

- (void)queryTrackInfoAction:(UIButton *)button {
    //查询Track信息
    AMapTrackQueryTrackInfoRequest *request = [[AMapTrackQueryTrackInfoRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = kAMapTrackTerminalID;
    request.startTime = ([[NSDate date] timeIntervalSince1970] - 12*60*60) * 1000;
    request.endTime = [[NSDate date] timeIntervalSince1970] * 1000;
    if (_correction) {
        request.correctionMode = @"denoise=1,mapmatch=1,threshold=0,mode=driving";
    }
    if (_recoup) {
        request.recoupMode = AMapTrackRecoupModeDriving;
    }
    
    [self.trackManager AMapTrackQueryTrackInfo:request];
}

- (void)queryTrackHisAction:(UIButton *)button {
    //查询历史轨迹和距离
    AMapTrackQueryTrackHistoryAndDistanceRequest *request = [[AMapTrackQueryTrackHistoryAndDistanceRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = kAMapTrackTerminalID;
    request.startTime = ([[NSDate date] timeIntervalSince1970] - 12*60*60) * 1000;
    request.endTime = [[NSDate date] timeIntervalSince1970] * 1000;
    if (_correction) {
        request.correctionMode = @"driving";
    }
    if (_recoup) {
        request.recoupMode = AMapTrackRecoupModeDriving;
    }
    
    [self.trackManager AMapTrackQueryTrackHistoryAndDistance:request];
}

- (void)correctionSegmentAction:(UISegmentedControl *)segmentControl {
    if (segmentControl.selectedSegmentIndex == 1) {
        _correction = YES;
    } else {
        _correction = NO;
    }
}

- (void)recoupSegmentAction:(UISegmentedControl *)segmentControl {
    if (segmentControl.selectedSegmentIndex == 1) {
        _recoup = YES;
    } else {
        _recoup = NO;
    }
}

#pragma mark - Helper

- (void)showPolylineWithTrackPoints:(NSArray<AMapTrackPoint *> *)points {
    int pointCount = (int)[points count];
    
    CLLocationCoordinate2D *allCoordinates = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < pointCount; i++) {
        allCoordinates[i].latitude = [[points objectAtIndex:i] coordinate].latitude;
        allCoordinates[i].longitude = [[points objectAtIndex:i] coordinate].longitude;
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:allCoordinates count:pointCount];
    [self.mapView addOverlay:polyline];
    
    if (allCoordinates) {
        free(allCoordinates);
        allCoordinates = NULL;
    }
}

#pragma mark - AMapTrackManagerDelegate

- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    NSLog(@"didFailWithError:%@; --- associatedRequest:%@;", error, request);
}

- (void)onQueryTrackHistoryAndDistanceDone:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request response:(AMapTrackQueryTrackHistoryAndDistanceResponse *)response {
    NSLog(@"onQueryTrackHistoryAndDistanceDone%@", response.formattedDescription);
    
    if ([[response points] count] > 0) {
        [self.mapView removeOverlays:[self.mapView overlays]];
        [self showPolylineWithTrackPoints:[response points]];
        [self.mapView showOverlays:self.mapView.overlays animated:NO];
    }
}

- (void)onQueryTrackInfoDone:(AMapTrackQueryTrackInfoRequest *)request response:(AMapTrackQueryTrackInfoResponse *)response {
    NSLog(@"onQueryTrackInfoDone%@", response.formattedDescription);
    
    [self.mapView removeOverlays:[self.mapView overlays]];
    for (AMapTrackBasicTrack *track in response.tracks) {
        if ([[track points] count] > 0) {
            [self showPolylineWithTrackPoints:[track points]];
        }
    }
    [self.mapView showOverlays:self.mapView.overlays animated:NO];
}

#pragma mark - MapView Delegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 12.f;
        
        return polylineRenderer;
    }
    
    return nil;
}

@end
